package com.agile.leetcode.tomcat.normalio;

import com.agile.leetcode.tomcat.servletscanner.AddressScanner;
import com.agile.leetcode.tomcat.abstractservlet.MyHttpServlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

/**
 * tomcat服务器
 *
 * @Author KD
 * @Date 2021/2/6 14:34
 */
public class Server {
    /**
     * 端口
     */
    private int port;

    public Server(int port) {
        this.port = port;
        // 首先扫描
        AddressScanner.scan("com.agile.leetcode.tomcat.servlet");
        System.out.println(AddressScanner.getAddress().size());
    }

    /**
     * 启动监听端口
     */
    public void start() throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        // 监听端口
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("接收到请求");
            // 新开线程去处理业务
            new Thread(() -> {
                try {
                    // 拿到输入流
                    InputStream inputStream = socket.getInputStream();
                    // 拿到输出流
                    OutputStream outputStream = socket.getOutputStream();
                    // 封装对象
                    MyRequest request = new MyRequest(inputStream);
                    MyResponse response = new MyResponse(outputStream);
                    doDispatch(request, response);
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private void doDispatch(MyRequest request, MyResponse response) throws IllegalAccessException, InstantiationException {
        Map<String, Class> map = AddressScanner.getAddress();
        // 拿到请求路径
        String url = request.getUrl();
        // 拿到最后一个地址
        int i = url.lastIndexOf("/");
        // 拿到地址
        String address = url.substring(i);
        // 拿到请求方法
        String method = request.getMethod();
        // 拿到字节码
        Class clazz = map.get(address);
        if (clazz != null) {
            MyHttpServlet instance = (MyHttpServlet) clazz.newInstance();
            instance.service(request, response);
        }
    }
}
